package org.example.quartz.job;

import org.example.domain.DiscussPost;
import org.example.service.imp.DiscussServiceImp;
import org.example.service.imp.ElasticSearchServerImp;
import org.example.service.imp.LikeServiceImp;
import org.example.util.CommonParam;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class HotDiscussScoreCompute implements Job {
    private static Logger logger = LoggerFactory.getLogger(HotDiscussScoreCompute.class);
    @Autowired
    private DiscussServiceImp discussServiceImp;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private LikeServiceImp likeServiceImp;
    @Autowired
    private ElasticSearchServerImp elasticSearchServerImp;
    //这个任务主要是处理 redis中被点赞的帖子 计算分数 然后存储mysql
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        Integer pop = (Integer)redisTemplate.boundSetOps(CommonParam.HOT_DISCUSS_KEY).pop();
        if (pop==null){
            logger.info("当前没有点整热帖需要处理分数 任务停止");
            return;
        }
        int tempCount = 0;
        while (pop!=null) {
            tempCount++;
            //处理分数 pop是帖子id  想要获取这个帖子的点赞 目前就处理了帖子点赞 为什么评论 和 关注不处理呢？ 因为我都不知道前面写的是什么代码了 哎 意思一下就行
            //这里主要是学会用quartz
            int likeCount = discussServiceImp.computeScore(pop);
            //默认点赞数就是分数
            discussServiceImp.updateScoreById(pop,(double)likeCount);
            //因为es中也是存储帖子的 需要更新一下
            DiscussPost discussPost = discussServiceImp.searchById(pop);
            elasticSearchServerImp.saveOneDiscussPost(discussPost);
            pop = (Integer)redisTemplate.boundSetOps(CommonParam.HOT_DISCUSS_KEY).pop();
        }
        logger.info("本次处理热帖数量为："+tempCount);
    }
}
